package cn.xetsoft.supermarket.util;

import org.apache.commons.lang3.StringUtils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

/**
 * @author 侯国强
 * @version 1.0
 * @Description 配置解析工具 例子： 服务.类型.属性 = 值
 * @since 2020/12/20 17:28
 */

public class PropertiesUtil {

    private static Properties props;
    private static String fileName;
    static {
        fileName = "SuperMarker.properties";
        props = new Properties();
        try {
            props.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName),"UTF-8"));
        } catch (IOException e) {
            //logger.error("配置文件读取异常",e);
        }
    }

    public static String getProperty(String key){
        String value = props.getProperty(key.trim());
        if(StringUtils.isBlank(value)){
            return null;
        }
        return value.trim();
    }

    public static String getProperty(String key,String defaultValue){

        String value = props.getProperty(key.trim());
        if(StringUtils.isBlank(value)){
            value = defaultValue;
        }
        return value.trim();
    }

    /**
     * 修改或者新增key
     * @param key
     * @param value
     */
    public static void update(String key, String value) {
        props.setProperty(key, value);
        FileOutputStream oFile = null;
        try {
            oFile = new FileOutputStream("src/main/resources/"+fileName);
            //将Properties中的属性列表（键和元素对）写入输出流
            props.store(oFile, "");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                oFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
